const express = require('express');

const util = require('../util');
const db = require('../db_helper');

const router = express.Router();
const logger = util.logger;

/**
 * 替换原有的 get|post 函数，由于原函数没有异常捕获，会出现
 */
function change (router, name){
  if (typeof(router[name]) === 'function'){
    router['__' + name] = router[name];
    router[name] = (url, fun) =>{
      router['__' + name](url, async (req, res, next)=>{
        try{
          logger.debug('request body:', req.body);
          let json = await fun(req.body, req, res);
          if (typeof(json) === 'string'){
            res.json({
              head: util.getErrMsg(json)
            });
          }else{
            res.json({
              head: util.sucResMsg,
              body: json || {}
            });    //如果执行过写入响应操作，在此处可以结束，如果已经写入，此处再次写入将无效
          }
        }catch(e){
          logger.error('error------>' ,e);
          res.json({
            head: util.getErrMsg('-99'),
            message: e.message,
            stack: e.stack
          });
          next();
        }
      });
    }
  }
}

change(router, 'get');
change(router, 'post');

router.get('/test', async(body, req, res) => {
  logger.debug('cookies: ', req.cookies);
  res.cookie('test', 'ttt')
})

router.post('/login', async (body, req, res)=>{
  let user = await db.getUser(body);
  if (body.psw === user.psw) {
    let token = util.signUser(user);
    //设置cookie
    if (body.user !== 'admin') {
      res.cookie('token', token, {
        maxAge: 365 * 24 * 3600,
        path: '/'
      })
    }
    return { token };
  }else{
    return '-1';    //密码错误
  }
});

router.get('/logout', (body, req, res) => {
  res.clearCookie('token', { path: '/'});
  res.redirect('/login.html')
})

router.post('/update-psw', async (body) =>{
  let user = await db.getUser(body);
  if (body.psw === user.psw){
    user.psw = body.newPsw;
    await db.updateUser(user);
  }else{
    return '-1';
  }
});

router.post('/all-user', async (body) =>{
  return await db.allUser();
});

router.post('/add-user', async (body) =>{
  return await db.addUser(body);
});

router.post('/update-user', async (body) =>{
  return await db.updateUser(body);
});

router.post('/del-user', async (body) =>{
  return await db.delUser(body);
});

router.post('/get-docs', (body) => {
  return db.loadAuth();
})

module.exports = router;
